<script setup>
import { ref } from 'vue';
import FormDrawer from '@/components/FormDrawer.vue';
import { connectCategoryGoodsAPI, deleteCategoryGoodsAPI, getCategoryGoodsAPI } from '@/api/category';
import { toast } from '@/composables/util';
import ChooseGoods from '@/components/ChooseGoods.vue';

const formDrawerRef = ref(null);
const category_id = ref(0)
const tableData = ref([])
const open = (item) => {
  category_id.value = item.id
  item.goodsDrawerLoading = true
  getData().then(res => {
    formDrawerRef.value.openDrawer()
  })
    .finally(() => {
      item.goodsDrawerLoading = false
    })
}
const getData = () => {
  return getCategoryGoodsAPI(category_id.value)
    .then(res => {
      tableData.value = res.map(o => {
        o.loading = false
        return o
      })
    })
}
const handleDelete = (row) => {
  row.loading = true
  deleteCategoryGoodsAPI(row.id)
    .then(res => {
      toast('删除成功')
      getData()
    })
}
const chooseGoodsRef = ref(null)
const handleConnect = () => {
  chooseGoodsRef.value.open((goods_ids) => {
    // console.log(goods_ids);
    formDrawerRef.value.showLoading()
    connectCategoryGoodsAPI({
      category_id: category_id.value,
      goods_ids
    })
      .then(res => {
        getData()
        toast('关联成功')
      })
      .finally(() => {
        formDrawerRef.value.hideLoading()
      })
  })
}
defineExpose({
  open
})
</script>

<template>
  <FormDrawer confirm-text="关联" @submit="handleConnect" ref="formDrawerRef" title="推荐商品">
    <el-table :data="tableData" border stripe style="width: 100%;">
      <el-table-column prop="goods_id" label="ID" width="60" />
      <el-table-column label="商品封面" width="180">
        <template #default="{ row }">
          <el-image :src="row.cover" fit="fill" :lazy="true" style="width: 64px; height: 64px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="180" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-popconfirm @confirm="handleDelete(row)" confirm-button-text="确认" cancel-button-text="取消" title="你确定要删除吗?">
            <template #reference>
              <el-button :loading="row.loading" text type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

  </FormDrawer>
  <ChooseGoods ref="chooseGoodsRef"></ChooseGoods>
</template>